require([
    'jquery',
    'global',
    'underscore',
    'bootstrap',
    'datatables.fixedcolumns',
    'requirejs/domready!'], 
function($, g, _) {
	
	var ticker = null, 
		select_mobile = '',
		order_table = null,
		order_fc_table = null;
	
	var start_tick = function(){
		$btn = $('#send-sms-btn');
		var sec = parseInt($btn.find('span.tick').text());
		sec--;
		if(sec <= 0 && ticker){
			clearInterval(ticker);
			$btn.empty()
				.prop('disabled', false)
				.append('发送短信验证码');
		}
		$btn.find('span.tick').text(sec+'');
	};
	
	$('#send-sms-btn').on('click', function(){
		var $form = $(this).parents('form'),
			$this = $(this);
		$.ajax({
			type: 'POST',
	    	url: g.context + '/order/send_sms',
	    	contentType: 'application/json; charset=utf-8',
	    	dataType : 'json',
	    	headers: {
	    		'x-form-id' : $form.attr('id')
	    	},
	    	data: JSON.stringify({
	    		mobile: $('#mobile-input').val() || null
	    	})
		}).done(function(result){
			if(result.code == 'ACK'){
				$this.empty()
					.prop('disabled', true)
					.append('<span class="tick">30</span>秒后重新发送');
				ticker = setInterval(start_tick, 1000);
			}
		});
	});
	
	$('#submit-btn').on('click', function(){
		var $form = $(this).parents('form');
		var d = {
			mobile: $form.find('input[name="mobile"]').val() || null,
			code: $form.find('input[name="code"]').val() || null
		};
		$.ajax({
			type: 'POST',
	    	url: g.context + '/order/validate_sms',
	    	contentType: 'application/json; charset=utf-8',
	    	dataType : 'json',
	    	headers: {
	    		'x-form-id' : $form.attr('id')
	    	},
	    	data: JSON.stringify(d)
		}).done(function(result){
			if(result.code == 'ACK'){
				select_mobile = d.mobile;
				$('#mobile-label').text(select_mobile);
				$('#order-table-panel').show();
				order_table.ajax.reload(null, false);
			}
		});
	});
	
	$('#order-table').on('click', 'tbody td', function(){
		var dt = $('#order-table').dataTable().api();
		var idx = dt.cell(this).index();
		if(!idx) return;
		var row = dt.row(idx.row).data();
		$(this).parents('tbody').find('tr.selected').removeClass('selected');
		$(this).parent().addClass('selected');
		var $ctr = $(this).parents('.DTFC_ScrollWrapper')
			.find('.DTFC_LeftBodyLiner .DTFC_Cloned tbody tr');
		$ctr.filter('.selected').removeClass('selected');
		$($ctr.get(idx.row)).addClass('selected');
	}).on('init.dt', function(){
		order_fc_table = new $.fn.dataTable.FixedColumns(
    		$('#order-table').dataTable().api(), {
				"iLeftColumns": 1,
				"iLeftWidth": 220
    		});
    }).on('draw.dt', function(){
    	if(order_table){
    		order_table.columns.adjust();
    	}
		if(order_fc_table){
			order_fc_table.fnRedrawLayout();
		}
    }).dataTable( {
    	language: {
            url: g.context + '/assets/js/chinese.json'
        },
        dom: 'rt<"row"<"col-md-4"i><"col-md-8"p>>',
    	processing : true,
	    serverSide : true,
	    scrollX: '100%',
		scrollCollapse : true,
	    ajax: {
	    	type: 'POST',
	    	url: g.context + '/orders',
	    	contentType: 'application/json; charset=utf-8',
	    	global: false,
	    	data: function(d){
	    		d.mobile = select_mobile;
	    		return JSON.stringify(d);
	    	},
	    	error: function(xhr, status, error){
	    		console.log(error);
	    	}
	    },
	    columnDefs: [ 
	     	{ targets : ['_all'], defaultContent: '&nbsp;', searchable : false }
	    ],
	    order: [[1, 'desc']],
	    columns: [
	        { data: 'orderId'},
	        { data: 'orderDate'},
	        { 
	          data: 'orderStatus', 
	          render: function(d, type, row){
	        	var t = '';
	        	switch(d){
	        		case '1':
	        			t = '接单';
	        			break;
	        		case '2':
	        			t = '待排裁剪计划';
	        			break;
	        		case '3':
	        			t = '裁剪';
	        			break;
	        		case '4':
	        			t = '缝纫';
	        			break;
	        		case '5':
	        			t = '后道';
	        			break;
	        		case '6':
	        			t = '仓库';
	        			break;
	        		case '7':
	        			t = '已发物流';
	        			break;
	        		default:
	        			break;
	        	}
	        	return t;
	          }
	        },
	        { data: 'productBrand'},
	        { data: 'agencyName'},
	        { data: 'carTypeName'},
	        { data: 'carTypeCode'},
	        { data: 'customerName'},
	        { data: 'receiverName'},
	        { data: 'receiverPhone'},
	        { data: 'receiverAddress'}
	    ]
    });
	order_table = $('#order-table').dataTable().api();
});